package com.flow.framework.schedule.executor;

import com.flow.framework.common.error.SystemErrorCode;
import com.flow.framework.common.exception.CheckedException;
import com.flow.framework.common.util.verify.VerifyUtil;
import com.flow.framework.core.system.initialization.ApplicationContextHelper;
import com.flow.framework.schedule.job.BaseScheduleJob;
import com.xxl.job.core.executor.XxlJobExecutor;
import com.xxl.job.core.glue.GlueFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

import java.util.Map;
import java.util.Set;

/**
 * RPC调度执行器
 *
 * @author luoguopiao
 * @version 0.0.1
 * @date 2022/4/9
 */
@Slf4j
public class RpcScheduleJobExecutor extends XxlJobExecutor implements InitializingBean, DisposableBean {

    @Override
    public void afterPropertiesSet() throws Exception {

        // init JobHandler Repository
        initRpcScheduleJobRepository();

        // refresh GlueFactory
        GlueFactory.refreshInstance(1);

        // super start
        super.start();
    }

    @Override
    public void destroy() {
        super.destroy();
    }


    private void initRpcScheduleJobRepository() {
        Map<String, BaseScheduleJob> beanNameAndBeanMap = ApplicationContextHelper.getBeanNameAndBeanMap(BaseScheduleJob.class);
        if (VerifyUtil.isEmpty(beanNameAndBeanMap)) {
            return;
        }
        Set<Map.Entry<String, BaseScheduleJob>> entries = beanNameAndBeanMap.entrySet();
        for (Map.Entry<String, BaseScheduleJob> entry : entries) {
            String beanName = entry.getKey();
            BaseScheduleJob bean = entry.getValue();
            bean.cacheSelf(bean);
            if (null != loadJobHandler(beanName)) {
                log.error("job name conflicts, name: {}", beanName);
                throw new CheckedException(SystemErrorCode.PARAMS_ERROR);
            }
            registJobHandler(beanName, bean);
        }
    }
}
